package com.gqz.utils;

import com.alibaba.fastjson.JSONObject;
import com.gqz.domain.SysOperLog;
import com.gqz.mapper.SysOperLogMapper;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Enumeration;
import java.util.Map;

@Aspect
@Component
public class WebLogAspect {

    @Autowired
    private SysOperLogMapper sysOperLogMapper;

    @Around("execution(* com.gqz.service.impl.*.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object proceed = joinPoint.proceed();
        saveLog(joinPoint);
        return proceed;
    }

    /**
     * 保存日志
     *
     * @param joinPoint
     */
    private void saveLog(ProceedingJoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        String realName = UserTools.getCurrentUserRealName(request);
        String url = request.getRequestURL().toString();
        String method = request.getMethod();


        new Thread(() -> {
            StringBuilder sb = new StringBuilder("请求了:" + className + "下的" + methodName + "方法\n");
            sb.append("{url:{")
                    .append(url)
                    .append("}, method:{")
                    .append(method)
                    .append("}}");

            SysOperLog log = new SysOperLog();
            log.setRealName(realName);
            log.setContent(sb.toString());
            log.setCreateTime(new Date());
            sysOperLogMapper.insert(log);
        }).start();

    }


}
